﻿using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using System.IO;

public class ResourceConfig {

	class ConfigData {

		private string _name;
		public string name {
			get { 
				return _name;
			}
		}

		private bool _isFromBundle;
		public bool isFromBundle {
			get {
				return _isFromBundle;
			}
		}

		private string _relativePath;
		public string relativePath {
			get {
				return _relativePath;
			}
		}

		public ConfigData(string name, bool isFromBundle, string relativePath) {
			this._name = name;
			this._isFromBundle = isFromBundle;
			this._relativePath = relativePath;
		}
	}

	private Dictionary<string, ConfigData> dicConfigData = new Dictionary<string, ConfigData> ();
	private string versionStr;

	public bool Load(string path) {
		string absolutePath;
		bool isExist = UnityPath.TryGetFile (path, out absolutePath);
		//Debug.Log ("ResourceConfig load isExist " + isExist);
		//Debug.Log ("ResourceConfig load absolutePath " + absolutePath);
		if (!isExist) {
			return false;		
		}
			
		string[] files = File.ReadAllLines (absolutePath);

		// version
		string[] splitStr0 = files[0].Split('|');
		if (splitStr0.Length == 2 && splitStr0 [0] == "version") {
			versionStr = splitStr0 [1];
		}

		// title


		for (int i = 2; i < files.Length; ++i) {
			string[] splitStr = files [i].Split ('|');
			if (splitStr.Length == 3) {
				bool isFromBundle;
				if (!bool.TryParse (splitStr [1], out isFromBundle)) {
					Debug.LogWarning ("ResourceConfig parse: bool parse error! line number is: " + i);
					Unload ();
					return false;
				}
				ConfigData data = new ConfigData (splitStr [0], isFromBundle, splitStr [2]);
				dicConfigData.Add (splitStr [0], data);
			} else {
				Debug.LogWarning ("ResourceConfig parse: line elements is not match! line number is: " + i);
				Unload ();
				return false;
			}
		}
	
		return true;
	}
		
	public void Unload() {
		dicConfigData.Clear ();
	}

	public bool GetFilePath(string fileName, out string filePath, out bool isFromBundle) {
		filePath = null;
		isFromBundle = false;
		ConfigData data = null;
		if (dicConfigData.TryGetValue (fileName, out data)) {
			filePath = data.relativePath;
			isFromBundle = data.isFromBundle;
			return true;
		}

		return false;
	}


}
